package com.program.facesigninsystem.controller;

import cn.yueshutong.springbootstartercurrentlimiting.annotation.CurrentLimiter;
import com.program.facesigninsystem.entity.ResponseModel;
import com.program.facesigninsystem.service.IUploadFileService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Mapler
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/files")
public class UploadFileController {
    @Resource
    private IUploadFileService iUploadFileService;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @CurrentLimiter(QPS = 5)
    public ResponseModel fileUpload(@RequestParam("file") MultipartFile file,@RequestParam("uid")String uid,@RequestParam("fileName")String fileName) {
        String url;
        //判断文件是否为空
        if (file.isEmpty()) {
            return new ResponseModel(172, "上传文件不可为空");
        }
        // 获取文件名
        String createTime =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String createTime1 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        fileName = createTime1.replace(" ","_") + "_" + fileName;
        //加个时间戳，尽量避免文件名称重复
        String path = "C:/uploadFiles/" +getFileType(file.getOriginalFilename())+"/"+uid+"/"+ fileName;
        //String path = "E:/fileUpload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
        //创建文件路径
        File dest = new File(path);
        //判断文件是否已经存在
        if (dest.exists()) {
            return new ResponseModel(171, "文件已存在");
        }
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            if(!dest.getParentFile().mkdir()){
                System.out.println("文件名不存在");
            }
        }
        try {
            file.transferTo(dest);
            url="http://47.103.218.55:8066/upload/"+getFileType(file.getOriginalFilename())+"/"+uid+"/"+ fileName;
            iUploadFileService.insertFile(uid,fileName, getFileType(fileName),path, url,transformSize(file.getSize()),createTime);

        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseModel(170, "上传失败");
        }
        return new ResponseModel(200, "上传成功");
    }

    @RequestMapping(value = "/fileList", method = RequestMethod.GET)
    @CurrentLimiter(QPS = 5)
    public ResponseModel fileList(@RequestParam("fileType")String type,@RequestParam("uid")String uid) {
        try {
            return new ResponseModel(200,"获取成功",iUploadFileService.fileList(uid,type));
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseModel(165,"获取失败");
        }
    }

    @RequestMapping(value = "/deleteFile", method = RequestMethod.GET)
    @CurrentLimiter(QPS = 5)
    public ResponseModel deleteFile(@RequestParam("filePath")String filePath,@RequestParam("uid")String uid) {
        try {
            File file = new File(filePath);
            if(!file.delete()) {
                return new ResponseModel(164,"删除失败");
            }
            iUploadFileService.deleteFile(uid,filePath);
            return new ResponseModel(200,"删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseModel(163,"删除失败");
        }
    }

    /**
     * 获取文件后缀名
     * @param filename 文件名
     * @return 返回后缀
     */
    private static String getFileType(String filename){
        if(filename == null){
            return "";
        }
        int pos = filename.lastIndexOf(".");
        if(pos == -1){
            return null;
        }
        return filename.substring(pos+1);
    }

    /**
     * 转换大小
     * @param size 文件大小
     * @return 返回转换后的大小
     */
    private static double transformSize(long size){
        double newSize = (double)size/(1024*1024);
        DecimalFormat df = new DecimalFormat("#.00");
        System.out.println(Double.parseDouble(df.format(newSize)));
        return Double.parseDouble(df.format(newSize));
    }
}
